package com.inspur.gs.sbssdl.database.rysj.rysj.front.queryunfinishedtasks.voactions;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.edp.bff.spi.AbstractFSAction;
import com.inspur.edp.caf.db.dbaccess.DynamicResultRow;
import com.inspur.edp.caf.db.dbaccess.IConverToListFunc;
import com.inspur.edp.caf.db.dbaccess.IDbParameter;
import com.inspur.edp.cef.entity.dependenceTemp.Pagination;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.qdp.bql.api.IBqlExecuter;
import com.inspur.edp.qdp.bql.api.OptionType;
import io.iec.edp.caf.runtime.config.BqlBeanUtil;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class GetErrorTasksVOAction extends AbstractFSAction<Object> {

    private String param;
    private final static String SELECT = "select BILLSTATUS,sbbh,sbmc,TYPE,startTime,endTime ";
    private final static String FROM = "from (select yb.BILLSTATUS,sbtz.sbbh,sbtz.sbmc,'一级保养' AS TYPE, \n" +
            " TO_DATE(yb.YEAR || '-' || LPAD(yb.month, 2, '0') || '-01', 'YYYY-MM-DD') AS startTime,\n" +
            " LAST_DAY(TO_DATE(yb.year || '-' || LPAD(yb.month, 2, '0') || '-01', 'YYYY-MM-DD')) AS endTime " +
            " from SBSS_SBYW_SBYJBYFK yb \n" +
            " LEFT JOIN SBSS_SBTZ_SBTZ sbtz on sbtz.id=yb.SBID  \n" +
            " UNION all " +
            " select eb.BILLSTATUS,sbtz.sbbh,sbtz.sbmc,'二级保养' AS TYPE,\n" +
            " TO_DATE(eb.YEAR || '-' || LPAD(eb.month, 2, '0') || '-01', 'YYYY-MM-DD') AS startTime,\n" +
            " LAST_DAY(TO_DATE(eb.year || '-' || LPAD(eb.month, 2, '0') || '-01', 'YYYY-MM-DD')) AS endTime\n" +
            " from SBSS_SBYW_SBEJBYFK eb \n" +
            " LEFT JOIN SBSS_SBTZ_SBTZ sbtz on sbtz.id=eb.SBID\n" +
            " UNION all\n" +
            " select rh.BillStatus,sbtz.sbbh,sbtz.sbmc,'设备润滑' AS TYPE,rhmx.startTime,rhmx.endTime  from SBSS_SBRH_TASK rh \n" +
            " LEFT JOIN SBSS_SBRH_TASKMX rhmx on rh.id = rhmx.ParentID\n" +
            " LEFT JOIN SBSS_SBTZ_SBTZ sbtz on sbtz.id=rh.dev\n" +
            " ) A  ";
    private String WHERE = " WHERE 1=1 AND A.BILLSTATUS <>2 AND A.BILLSTATUS <>3 ";
    private IBqlExecuter bqlExecuter = BqlBeanUtil.getAppCtx().getBean(IBqlExecuter.class);

    public GetErrorTasksVOAction(String param) {
        this.param = param;
    }

    @Override
    public void execute() {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = null;
        try {
            map = mapper.readValue(param, Map.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e.getMessage());
        }
        int pageIndex = Integer.parseInt(map.get("pageIndex").toString());
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        Pagination pageInfo = new Pagination(pageSize, pageIndex);
        // 查询数据
        ArrayList<IEntityData> rows = queryData(pageInfo);
        // 查询数据总数
        int count = queryCount();
        pageInfo.setPageCount(rows.size());
        pageInfo.setTotalCount(count);
        HashMap<String, Object> queryresult = new HashMap<>();
        queryresult.put("queryresult", rows);
        queryresult.put("pageInfo", pageInfo);
        setResult(queryresult);
    }

    private ArrayList<IEntityData> queryData(Pagination pagination) {
        List<IDbParameter> params = new ArrayList<>();
        StringBuilder sql = new StringBuilder(SELECT + FROM);
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
        String dateString = dateFormat.format(date);
        WHERE += "and A.endTime< TO_DATE('" + dateString + "', 'YYYY-MM-DD') ";
        bqlExecuter.getOptions().setOptionType(OptionType.ExecuteSql);
        List<IEntityData> data = bqlExecuter.executeSelectStatement(appendPagination(sql, pagination), getIds(),
                new Iconver(), params.toArray(new IDbParameter[]{}));
        return new ArrayList<>(data);
    }

    private int queryCount() {
        List<IDbParameter> params = new ArrayList<>();
        String sql = "select count(*) as count " + FROM + WHERE;
        bqlExecuter.getOptions().setOptionType(OptionType.ExecuteSql);
        List<DynamicResultRow> rows = bqlExecuter.executeSelectStatement(sql, getIds(),
                params.toArray(new IDbParameter[]{}));
        for (DynamicResultRow row : rows) {
            if (row.get("count") != null) {
                return Integer.valueOf(row.get("count").toString());
            }
        }
        return 0;
    }

    private List<String> getIds() {
        ArrayList<String> arrayList = new ArrayList<>();
//        arrayList.add("84ec34b9-d139-4216-8d69-09ec8145eab1");
//        arrayList.add("cde823e0-7159-4c28-b411-165d30abfe4c");
        return arrayList;
    }

    private String appendPagination(StringBuilder sql, Pagination pagination) {
        if (pagination == null) {
            pagination = new Pagination(20, 1);
        }
        int offset = pagination.getPageSize() * (pagination.getPageIndex() - 1);
        sql.append(WHERE).append(" order by A.startTime DESC, A.endTime DESC ")
                .append(" offset ")
                .append(offset)
                .append(" rows FETCH NEXT ")
                .append(pagination.getPageSize()
                ).append(" ROWS ONLY ");
        return sql.toString();
    }


    public class Iconver implements IConverToListFunc<IEntityData> {

        @Override
        public List<IEntityData> convert(List<DynamicResultRow> list) {
            ArrayList<IEntityData> entityData = new ArrayList<>();
            if (!list.isEmpty()) {
                for (DynamicResultRow resultRow : list) {
                    IEntityData voEntityData = getContext().createData();
                    if (resultRow.get("BILLSTATUS") != null)
                        voEntityData.setValue("BILLSTATUS", resultRow.get("BILLSTATUS"));
                    if (resultRow.get("startTime") != null)
                        voEntityData.setValue("startTime", resultRow.get("startTime"));
                    if (resultRow.get("endTime") != null)
                        voEntityData.setValue("endTime", resultRow.get("endTime"));
                    if (resultRow.get("sbbh") != null)
                        voEntityData.setValue("sbbh", resultRow.get("sbbh"));
                    if (resultRow.get("sbmc") != null)
                        voEntityData.setValue("sbmc", resultRow.get("sbmc"));
                    if (resultRow.get("TYPE") != null)
                        voEntityData.setValue("TYPE", resultRow.get("TYPE"));
                    entityData.add(voEntityData);
                }
            }
            return entityData;
        }
    }
}
